/*
 Copyright (C) 2009 QDSS.org
 
 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 
 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.qdss.persist.query;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.qdss.persist.Entity;
import org.qdss.persist.engine.ID;
import org.qdss.persist.engine.SqlExecutorContext;
import org.qdss.persist.engine.StandardRecord;
import org.qdss.persist.query.compiler.QueryCompiler;
import org.qdss.persist.query.compiler.SelectItem;

/**
 * 
 * 
 * @author <a href="mailto:zhaofang123@gmail.com">FANGFANG ZHAO</a>
 * @since 0.1, Mar 8, 2009
 * @version $Id: CapriciousRecord.java 119 2011-05-15 16:56:18Z zhaofang123@gmail.com $
 */
public class CapriciousRecord extends StandardRecord {

	private final Map<String, Object> idLabel = new HashMap<String, Object>();
	private SelectItem[] selectItems;

	protected CapriciousRecord(Entity entity, SqlExecutorContext context) {
		super(entity, null);
	}
	
	public void setSelectItems(SelectItem[] selectItems) {
		this.selectItems = selectItems.clone();
	}
	
	public SelectItem[] getSelectItems() {
		return selectItems.clone();
	}

	@Override
	protected void setObject(String key, Object value) {
		Entity e = getEntity();
		if (e.containsField(key)) {
			super.setObject(key, value);
			return;
		}

		if (key.charAt(0) == QueryCompiler.NAMED_FIELD_PREFIX) {
			key = key.substring(1);
			ID id = getID(key);
			if (id != null)
				id.setLabel(value.toString());
			else
				idLabel.put(key, value);
		} else {
			recordMap.put(key, value);
		}
	}

	@Override
	protected Object getObject(String key, Class<?> clazz) {
		Entity e = getEntity();
		if (e.containsField(key))
			return super.getObject(key, clazz);

		return recordMap.get(key);
	}

	/**
	 * 
	 */
	protected void complete() {
		if (idLabel.isEmpty())
			return;
		for (Iterator<Map.Entry<String, Object>> iter = idLabel.entrySet()
				.iterator(); iter.hasNext();) {
			Map.Entry<String, Object> e = iter.next();
			ID id = getID(e.getKey());
			if (id != null)
				id.setLabel(e.getValue().toString());
		}
	}
}
